import os

def is_text_file(file_path):
    """
    判断文件是否为文本文件。尝试读取文件的前一部分并捕获异常，
    如果无法读取，则认为是二进制文件。
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            file.read(1024)  # 尝试读取前1024个字符
        return True  # 是文本文件
    except (UnicodeDecodeError, OSError):
        return False  # 是二进制文件

def rename_files_and_content_recursively(folder_path, old_str, new_str):
    """
    递归替换文件夹及其子文件夹内文件名和文件内容中的指定字符串。

    :param folder_path: 文件夹路径
    :param old_str: 需要替换的字符串
    :param new_str: 替换为的新字符串
    """
    try:
        for root, dirs, files in os.walk(folder_path):
            for filename in files:
                old_file_path = os.path.join(root, filename)

                # 替换文件名
                if old_str in filename:
                    new_file_name = filename.replace(old_str, new_str)
                    new_file_path = os.path.join(root, new_file_name)
                    os.rename(old_file_path, new_file_path)
                    print(f"Renamed: '{old_file_path}' -> '{new_file_path}'")
                    old_file_path = new_file_path  # 更新为新的文件路径

                # 仅处理文本文件
                if is_text_file(old_file_path):
                    # 替换文件内容
                    with open(old_file_path, 'r', encoding='utf-8') as file:
                        content = file.read()

                    if old_str in content:
                        # 替换文件内容中的指定字符串
                        updated_content = content.replace(old_str, new_str)

                        # 重新写回文件
                        with open(old_file_path, 'w', encoding='utf-8') as file:
                            file.write(updated_content)
                        print(f"Content in '{old_file_path}' updated.")
                else:
                    print(f"Skipping binary file: '{old_file_path}'")
    
    except Exception as e:
        print(f"Error: {e}")

# 示例用法
folder_path = r'D:\xiugaiUUID\ZeusSuper'  # 替换为目标文件夹路径
old_str = "ZeusSuper"  # 替换为需要替换的字符串
new_str = "Zeus"       # 替换为新的字符串

rename_files_and_content_recursively(folder_path, old_str, new_str)
